import json
import re
from django import http
from django.contrib.auth import login, logout, authenticate
from django.db import DatabaseError
from django.views import View
from ihome.utils.views import LoginRequiredMixin
from ihome.utils.fdfs.fastdfs_storage import FDFSStorage
from ihome.utils.response_code import RET
from users.models import User





class RegisterAPIView(View):

    def post(self, request):
        """
        实现用户注册
        :param request: 请求对象
        :return: 注册结果
        """
        # username = request.POST.get('username')
        # mobile = request.POST.get('mobile')
        # password = request.POST.get('password')
        # password2 = request.POST.get('password2')
        # allow = request.POST.get('allow')
        json_str = request.body
        json_str = json_str.decode()  # python3.6 无需执行此步
        req_data = json.loads(json_str)
        mobile = req_data['mobile']
        password = req_data['password']
        password2 = req_data['password2']
        phonecode = req_data['phonecode']

        # 判断参数是否齐全
        if not all([ password, password2, mobile,phonecode]):
            return http.HttpResponseForbidden('缺少必传参数')
        # 判断用户名是否是5-20个字符
        # if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
        #     return http.HttpResponseForbidden('请输入5-20个字符的用户名')
        # 判断密码是否是8-20个数字
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseForbidden('请输入8-20位的密码')
        # 判断两次密码是否一致
        if password != password2:
            return http.HttpResponseForbidden('两次输入的密码不一致')
        # 判断手机号是否合法
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('请输入正确的手机号码')
        # 判断是否勾选用户协议
        # if allow != 'on':
        #     return http.HttpResponseForbidden('请勾选用户协议')
        # 短信验证码
        # 1.读取redis中的短信验证码
        # redis_cli = get_redis_connection('sms_code')
        # sms_code_redis = redis_cli.get(mobile)
        # # 2.判断是否过期
        # if sms_code_redis is None:
        #     return http.HttpResponseForbidden('短信验证码已经过期')
        # # 3.删除短信验证码，不可以使用第二次
        # redis_cli.delete(mobile)
        # redis_cli.delete(mobile + '_flag')
        # # 4.判断是否正确
        # if sms_code_redis.decode() != sms_code:
        #     return http.HttpResponseForbidden('短信验证码错误')



        # 保存注册数据
        try:
            user = User.objects.create_user(password=password, mobile=mobile, username=mobile)
        except DatabaseError:
            return http.JsonResponse({'errno': RET.PWDERR,
                                'register_errmsg': '注册失败'})

        login(request, user)

        # 响应注册结果
        return http.JsonResponse(
            {
                'errno': RET.OK,
                'errmsg': "注册成功"
            }
        )

class GetLoginView(View):
    '''获取登录状态API'''
    def get(self,request):

        user = request.user

        if user == None:
            return http.JsonResponse({
                "errno": "4101",
                "errmsg": "未登录"
            })
        else:
            data={
                'user_id' : user.id ,
                "name": user.username
            }
            return http.JsonResponse({
                "errno": "0", "errmsg": "OK", "data": data
            })

class LogoutView(View):
    """退出登录"""

    def delete(self, request):
        """实现退出登录逻辑"""


        user = request.user
        if user == None:
            return http.JsonResponse({
                'errno': RET.SESSIONERR,
                'errmsg': '用户未登录'})

        else:
        # 清理 session
            logout(request)
            return http.JsonResponse(
                {'errno': RET.OK, 'errmsg': "用户已退出"}
            )





class LoginView(View):
    """用户名登录"""

    # def get(self, request):
    #     """提供登录界面的接口"""
    #     # 返回登录界面
    #     return render(request, 'login.html')

    def post(self,request):

        json_str = request.body
        json_str = json_str.decode()  # python3.6 无需执行此步
        req_data = json.loads(json_str)
        mobile = req_data['mobile']
        password = req_data['password']

        # 校验参数
        # 判断参数是否齐全
        # 所以我们不对它是否存在进行判断:


        if not all([ password,mobile]):
            return http.HttpResponseForbidden('缺少必传参数')

        if not re.match(r'^1[3-9]\d{9}$',mobile):
            return http.HttpResponseForbidden('手机号不对')

        # 判断密码是否是8-20个数字
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseForbidden('密码最少8位，最长20位')

        # 认证登录用户
        username = User.objects.get(mobile = mobile).username
        user = authenticate(username = username,password=password)
        if user is None:
            return http.JsonResponse({'account_errmsg': '没有这个用户'})

        # 实现状态保持
        login(request, user)
        # # 设置状态保持的周期
        # if remembered != 'on':
        #     # 不记住用户：浏览器会话结束就过期
        #     request.session.set_expiry(0)
        # else:
        #     # 记住用户：None 表示两周后过期
        #     request.session.set_expiry(None)

        # 响应登录结果
        return http.JsonResponse(
            {
                'errno': RET.OK,
                'errmsg': "登陆成功"
            }
        )

    #
















# class UserInfoView(View):
class UserInfoView(LoginRequiredMixin,View):
    """用户中心"""

    def get(self, request):
        """提供个人信息界面"""



        data = {
            'name': request.user.username,
            'mobile': request.user.mobile,
            'avatar_url': request.user.avatar_url,
        }

        # 返回响应
        return http.JsonResponse({"errno":'0',
                                'errmsg':'OK',
                                'data':data
                                })


    def post(self,request):
        """用户名更改"""
        json_dict = json.loads(request.body.decode())
        new_name = json_dict.get('name')

        # 参数校验
        if new_name ==None:
            return http.JsonResponse({"errno":'RET.PARAMERR',
                                'errmsg':'参数不完整'})

        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', new_name):
            return http.JsonResponse({"errno": 'RET.PARAMERR',
                                      'errmsg': '参数检验失败'})
        try:
            # # 假数据
            # user = User.objects.get(username='python')
            user = request.user
            user.username = new_name
            user.save()
        except Exception:
            return http.JsonResponse({"errno": 'RET.DATAERR',
                                      'errmsg': '数据库保存失败'})


        return http.JsonResponse({'errno':RET.OK,'errmsg':'OK'})



class UserImageView(LoginRequiredMixin,View):
    def post(self, request):
        data = request.FILES
        avatar_obj = data.get('avatar')

        if not avatar_obj:
            return http.JsonResponse({"errno": 'RET.NODATA',
                                      'errmsg': '无图片'})
        storage = FDFSStorage()

        file_id = storage._save(avatar_obj.name,avatar_obj)

        avatar_url = storage.url(file_id)

        try:
            user = request.user
            user.avatar_url = avatar_url
            user.save()
        except Exception:
            return http.JsonResponse({"errno": 'RET.DATAERR',
                                      'errmsg': '数据库保存失败'})
        return http.JsonResponse({"errno": 'RET.OK',
                                      'errmsg': 'ok',
                                  'data':{'avatar_url':'avatar_url'}}
                                 )

class UserauthView(LoginRequiredMixin,View):


    def get(self,request):
        user = request.user
        data = {
            'real_name' : user.real_name,
            'id_card':user.id_card
        }

        return http.JsonResponse({"errno": 0,
                                "errmsg":"success",
                                "data":data})

    def post(self,request):

        json_dict = json.loads(request.body.decode())
        real_name = json_dict.get('real_name')
        id_card = json_dict.get('id_card')


        if not all([real_name,id_card]):
            return http.JsonResponse({"errno": 'RET.PARAMERR',
                                      'errmsg': '参数不完整'})

        if not re.match(r'^([\u4e00-\u9fa5]){2,7}$', real_name):
            return http.JsonResponse({"errno": 'RET.PARAMERR',
                                      'errmsg': '参数检验失败'})
        if not re.match(r'^[0-9]{17}[0-9X]$', id_card):
            return http.JsonResponse({"errno": 'RET.PARAMERR',

                                      'errmsg': '参数检验失败'})

        user = request.user

        user.real_name = real_name
        user.id_card = id_card
        user.save()


        return http.JsonResponse({'errno':RET.OK,'errmsg':'OK'})



















